package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequirePermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.javassist.bytecode.stackmap.BasicBlock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author L5775
 */
@Controller
public class LoginController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    // 处理保存或修改请求
    // http://localhost/employee/saveOrUpdate.do 并带了保存员工数据
    // 保存完了还希望浏览器再发送请求访问 localhost/employee/list.do
    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password){
        try {
            Employee employee = employeeService.login(username,password);
            //存放到session中
            //session.setAttribute("USER_IN_SESSION",employee);
            UserContext.setCurrentUser(employee);
            if (!employee.isAdmin()) { //如果不是管理员才查询权限
                //获取用户拥有的权限表达式列表
                List<String> expressions = permissionService.selectByEmpId(employee.getId());
                //存放到session中
                //session.setAttribute("EXPRESSION_IN_SESSION",expressions);
                UserContext.setExpressions(expressions);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,e.getMessage());
        }
    }
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();//销毁回话
        return "redirect:/login.html";
    }
}
